package com.ccys.common.third.push.huawei;



import com.alibaba.fastjson.JSONObject;
import com.ccys.common.third.push.huawei.push.exception.HuaweiMesssagingException;
import com.ccys.common.util.RestUtil;
import com.ccys.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 从官网获取的APP_KEY
 * <p>
 * 参考文档：https://support.huaweicloud.com/api-iam/iam_03_0001.html
 * https://developer.huawei.com/consumer/cn/doc/service/oauth-0000001240070027
 * 示例代码： https://gitee.com/hms-core/hms-push-serverdemo-java
 * https://gitee.com/hms-core/hms-push-serverdemo-java#1-%E5%8F%91%E9%80%81android%E9%80%8F%E4%BC%A0%E6%B6%88%E6%81%AF
 * 已测试通过
 * @author Administrator
 */
@Slf4j
@Component
public class HuaweiPushTest {
    // You need to replace these with your configurations
    private static final String HMS_TOKEN_URL = "https://login.cloud.huawei.com/oauth2/v2/token";
    private static final String HMS_CLIENT_ID = "104955689";
    private static final String HMS_CLIENT_SECRET = "6c4989112e867886f56717155772a16c44993f8220617bd5ab4b7e82d7621eb0";
    private static final String HMS_NOTIFICATION_URL = "Your notification URL here"; // You should define this

    public boolean sendHMS_Customer(List<String> gcmTokens, String pushMessage, int pushType, String booking_id, String booking_type, String service_type, String push_id) {
        boolean returnVal = true;
        String sound = "default";
        String accessToken = HMS_GetToken();
        for (int i = 0; i < gcmTokens.size(); i += 1000) {
            List<String> tokens = gcmTokens.subList(i, Math.min(i + 1000, gcmTokens.size()));
            List<String> tokenStrings = tokens.stream().map(token -> "\"" + token + "\"").collect(Collectors.toList());
            String joinedTokens = String.join(",", tokenStrings);
            StringBuilder sbPostData = new StringBuilder();
            sbPostData.append("{ \"validate_only\": false, ");
            sbPostData.append("\"message\": {");
            sbPostData.append("\"data\": \"{");
            if (booking_id != null && !booking_id.isEmpty()) {
                sbPostData.append("'key_id': '" + booking_id + "',");
            }
            if (service_type != null && !service_type.isEmpty()) {
                sbPostData.append("'service_type': '" + service_type + "', ");
            }
            if (push_id != null && !push_id.isEmpty()) {
                sbPostData.append("'push_id': '" + push_id + "', ");
            }
            sbPostData.append("'type': '" + pushType + "', ");
            sbPostData.append("'message': '" + pushMessage + "', ");
            sbPostData.append("'sound': '" + sound + "', ");
            sbPostData.append("'timestamp': '" + System.currentTimeMillis() + "'}\",");
            sbPostData.append("\"android\": {");
            String fastAppTarget = "1"; // You should fetch this from your configuration
            sbPostData.append("\"fast_app_target\": " + fastAppTarget + "},");
            sbPostData.append("\"token\": [ " + joinedTokens + " ]}}");

            try {
                URL url = new URL(String.format(HMS_NOTIFICATION_URL, HMS_CLIENT_ID));
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Authorization", accessToken);
                connection.setDoOutput(true);

                OutputStream os = connection.getOutputStream();
                os.write(sbPostData.toString().getBytes());
                os.flush();
                os.close();

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    log.info("response send HMS : " + response.toString());
                } else {
                    log.warn("Failed : HTTP error code : " + responseCode);
                    returnVal = false;
                    break;
                }
            } catch (Exception e) {
                log.error("Send HMS Notification Error: " + e.toString());
                returnVal = false;
                break;
            }
        }
        return returnVal;
    }



    public boolean sendHMSCustomer(List<String> gcmTokens, String pushMessage, int pushType, String booking_id, String booking_type, String service_type, String push_id) {
        boolean returnVal = true;
        String sound = "default";
        String accessToken = HMS_GetToken();
        for (int i = 0; i < gcmTokens.size(); i += 1000) {
            List<String> tokens = gcmTokens.subList(i, Math.min(i + 1000, gcmTokens.size()));
            List<String> tokenStrings = tokens.stream().map(token -> "\"" + token + "\"").collect(Collectors.toList());
            String joinedTokens = String.join(",", tokenStrings);
            StringBuilder sbPostData = new StringBuilder();
            sbPostData.append("{ \"validate_only\": false, ");
            sbPostData.append("\"message\": {");
            sbPostData.append("\"data\": \"{");
            if (booking_id != null && !booking_id.isEmpty()) {
                sbPostData.append("'key_id': '" + booking_id + "',");
            }
            if (service_type != null && !service_type.isEmpty()) {
                sbPostData.append("'service_type': '" + service_type + "', ");
            }
            if (push_id != null && !push_id.isEmpty()) {
                sbPostData.append("'push_id': '" + push_id + "', ");
            }
            sbPostData.append("'type': '" + pushType + "', ");
            sbPostData.append("'message': '" + pushMessage + "', ");
            sbPostData.append("'sound': '" + sound + "', ");
            sbPostData.append("'timestamp': '" + System.currentTimeMillis() + "'}\",");
            sbPostData.append("\"android\": {");
            String fastAppTarget = "1"; // You should fetch this from your configuration
            sbPostData.append("\"fast_app_target\": " + fastAppTarget + "},");
            sbPostData.append("\"token\": [ " + joinedTokens + " ]}}");

            try {
                URL url = new URL(String.format(HMS_NOTIFICATION_URL, HMS_CLIENT_ID));
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Authorization", accessToken);
                connection.setDoOutput(true);

                OutputStream os = connection.getOutputStream();
                os.write(sbPostData.toString().getBytes());
                os.flush();
                os.close();

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    log.info("response send HMS : " + response.toString());
                } else {
                    log.warn("Failed : HTTP error code : " + responseCode);
                    returnVal = false;
                    break;
                }
            } catch (Exception e) {
                log.error("Send HMS Notification Error: " + e.toString());
                returnVal = false;
                break;
            }
        }
        return returnVal;
    }

       /**
        * @description 获取访问token
        * @date     2024/1/13
        * @author   cloud fly
        * return  请求结果：{"access_token":"DAEBAF9Yq1tZ3ZUkGc8Z8CgVl1dCDhzWwf5XW+2r7FVYMuatzwBpQPXhLuEa4rhGd96fRhF1+RcXDeiqTa9Ph/mejvJJpkBwl947gQ==","token_type":"Bearer","expires_in":3600}
        */
    public static String HMS_GetToken() {
        try {
            Map<String, String> headerMap = new HashMap<>();
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("grant_type","client_credentials");
            //进行URL编码
            String clientId = URLEncoder.encode(HuaweiPushTest.HMS_CLIENT_ID, "UTF-8");
            String clientSecret = URLEncoder.encode(HuaweiPushTest.HMS_CLIENT_SECRET, "UTF-8");
            paramMap.put("client_id",clientId);
            paramMap.put("client_secret",clientSecret);
            String result = RestUtil.executeForm(HuaweiPushTest.HMS_TOKEN_URL, HttpMethod.POST, headerMap, paramMap);
            System.out.println("网络请求结果：" + result);
            if(StringUtil.isNotEmpty(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if(jsonObject != null) {
                    return jsonObject.get("access_token").toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args)  {
        String pushToken="IQAAAACy0n3JAABJnxF_ibWhDJ0lI_4-GkuTuO62bd8YpWldlU6o3Uu_WH26sH3HG1FYaMMisDIopdyUBvVw6I36S-wpF93uPQC5hWVff1QaD1uI0w";
        List<String> tokenList = new ArrayList<>();
        tokenList.add(pushToken);

        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("id","16");
            jsonData.put("type","0");
            HuaWeiPush.pushToByToken("这是一个标题","这是推送具体内容",jsonData.toJSONString(),tokenList);
            //测试透传消息
            //HuaWeiPush.sendTransparent(pushToken,jsonData.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*String token = HuaweiNotificationUtil.HMS_GetToken();
        System.out.println("获取的访问token：" + token );*/

    }


}